package com.groupbuying.redpacket.service.impl;

import com.groupbuying.redpacket.dao.RedPacketRuleDao;
import com.groupbuying.redpacket.domain.RedPacketRuleDO;
import com.groupbuying.redpacket.domain.RedPacketTaskDO;
import com.groupbuying.redpacket.service.RuleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author: mayunfei
 * @Date: Create in 16:57 2019/11/12
 * @tar:
 */
@Service
public class RuleServiceImpl implements RuleService {
    public static final Logger LOGGER = LoggerFactory.getLogger(RuleServiceImpl.class);

    @Autowired
    private RedPacketRuleDao redPacketRuleDao;

    /**
     * 根据TaskId查询rule
     */
    @Override
    public List<RedPacketRuleDO> rulebyTaskId(String taskId) {
        LOGGER.info("打印传参红包taskId:{}", taskId);
        if (StringUtils.isEmpty(taskId)) {
            LOGGER.error("红包信息为空! 红包taskId{}", taskId);
            return null;
        }
        List<RedPacketRuleDO> redPacketRuleDO = redPacketRuleDao.ruleByTaskId(taskId);
        if (redPacketRuleDO == null) {
            LOGGER.error("红包信息不存在！");
            return null;
        }
        return redPacketRuleDO;
    }

    /**
     * 批量添加
     */
    @Override
    public int insertBatch(RedPacketTaskDO redPacketTaskDO, List<RedPacketRuleDO> redPacketRuleDO) {
        if (redPacketRuleDO == null) {
            LOGGER.error("参数为空！");
            return 0;
        }
        Long id = redPacketTaskDO.getId();
        String TaskId = Long.toString(id);
        List<RedPacketRuleDO> list = new ArrayList<>();
        for (RedPacketRuleDO list1 : redPacketRuleDO) {
            list1.setTaskId(TaskId);
            Integer totalCount = list1.getTotalCount();
            if (totalCount > 0) {
               list.add(list1);
            }
        }
        return redPacketRuleDao.insertBatch(list);
    }

    /**
     * 根据taskId物理删除Rule
     */
    @Override
    public int deleteByTaskId(String taskId) {
        LOGGER.info("打印传参红包taskId:{}", taskId);
        if (StringUtils.isEmpty(taskId)) {
            LOGGER.error("红包信息为空! 红包taskId{}", taskId);
            return 0;
        }
        return redPacketRuleDao.deleteByTaskId(taskId);
    }


}
